<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible.sync="showExcelDialog"
  >
    <el-row type="flex" justify="center">
      <el-upload
        ref="excel-upload-input"
        action=""
        class="upload-excel"
        :show-file-list="false"
        :auto-upload="false"
        accept=".xlsx, .xls"
        drag
        :limit="1"
        :on-change="onUploadFile"
      >
        <i class="el-icon-upload" />
        <div>
          <!-- .stop阻止点击下载时会出现选择文件 -->
          <el-button
            type="text"
            @click.stop="downloadTemplate"
          >下载导入模板</el-button>
        </div>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
    </el-row>
    <el-row type="flex" justify="end">
      <!-- update:props属性名，值 直接修改 .sync修饰符的属性值 -->
      <el-button size="mini" type="primary" @click="showExcelDialog = false">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { downloadTemplate, importUser } from '@/api/employee'
import FileSaver from 'file-saver'
export default {
  data() {
    return {
      showExcelDialog: false,
      file: null
    }
  },
  methods: {
    open() {
      this.showExcelDialog = true
    },
    async downloadTemplate() {
      const res = await downloadTemplate()
      FileSaver.saveAs(res, '员工信息模板.xlsx')
    },
    async onUploadFile(file) {
      if (file.raw.name) {
        const fd = new FormData()
        fd.append('file', file.raw)
        try {
          await importUser(fd)
          this.$message.success('文件上传成功')
          this.showExcelDialog = false
          this.$emit('dataUpload')
        } catch (e) {
          console.log(e)
        } finally {
          // 清除文件
          this.$refs['excel-upload-input'].clearFiles()
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.upload-excel {
  display: flex;
  justify-content: center;
  margin: 20px;
  width: 360px;
  height: 180px;
  align-items: center;
  color: #697086;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #dcdfe6;
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 160px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .drop {
    line-height: 40px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
      color: #c0c4cc;
    }
  }
}
</style>
